import {
  apiInterceptors,
  delApp,
  getAppAdmins,
  getAppList,
  newDialogue,
  publishApp,
  unPublishApp,
  updateAppAdmins,
} from '@/client/api';
import BlurredCard, { ChatButton, InnerDropdown } from '@/new-components/common/blurredCard';
import System from '@/new-components/layout/System';
import { IApp } from '@/types/app';
import { BulbOutlined, DingdingOutlined, PlusOutlined, SearchOutlined, WarningOutlined } from '@ant-design/icons';
import { useDebounceFn, useRequest } from 'ahooks';
import { App, Button, Input, Modal, Pagination, Popover, Segmented, SegmentedProps, Select, Spin, Tag } from 'antd';
import copy from 'copy-to-clipboard';
import moment from 'moment';
import { useRouter } from 'next/router';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CreateRoleModal from './create-role-modal/index';

type ModalType = 'edit' | 'add';

export default function RoleContent() {
  const router = useRouter();
  const { openModal = '' } = router.query;
  const { t } = useTranslation();
  const { message } = App.useApp();

  const [open, setOpen] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [roles, setRoles] = useState<IApp[]>([]);
  const [modalType, setModalType] = useState<ModalType>('add');
  const [filterValue, setFilterValue] = useState('');
  const [admins, setAdmins] = useState<string[]>([]);

  // 分页信息
  const totalRef = useRef<{
    current_page: number;
    total_count: number;
    total_page: number;
  }>();

  const handleCreate = () => {
    setModalType('add');
    setOpen(true);
  };

  const getListFiltered = useCallback(() => {
    initData({ app_name: filterValue });
  }, [filterValue]);


  // 发布或取消发布应用
  const { run: operate } = useRequest(
    async (app: IApp) => {
      if (app.published === 'true') {
        return await apiInterceptors(unPublishApp(app.app_code));
      } else {
        return await apiInterceptors(publishApp(app.app_code));
      }
    },
    {
      manual: true,
      onSuccess: data => {
        if (data[2]?.success) {
          message.success('操作成功');
        }
        getListFiltered();
      },
    },
  );

  const initData = useDebounceFn(
    async params => {
      setSpinning(true);
      const obj: any = {
        page: 1,
        page_size: 12,
        ...params,
      };
      const [error, data] = await apiInterceptors(getAppList(obj));
      if (error) {
        setSpinning(false);
        return;
      }
      if (!data) return;
      setRoles(data?.app_list || []);
      totalRef.current = {
        current_page: data?.current_page || 1,
        total_count: data?.total_count || 0,
        total_page: data?.total_page || 0,
      };
      setSpinning(false);
    },
    {
      wait: 500,
    },
  ).run;

  const showDeleteConfirm = (app: IApp) => {
    Modal.confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: t('want_delete'),
      okText: t('verify'),
      okType: 'danger',
      cancelText: t('cancel'),
      async onOk() {
        await apiInterceptors(delApp({ app_code: app.app_code }));
        getListFiltered();
      },
    });
  };

  useEffect(() => {
    if (openModal) {
      setModalType('add');
      setOpen(true);
    }
  }, [openModal]);

  const onSearch = async (e: any) => {
    const v = e.target.value;
    setFilterValue(v);
  };

  // 获取应用权限列表
  const { run: getAdmins, loading } = useRequest(
    async (appCode: string) => {
      const [, res] = await apiInterceptors(getAppAdmins(appCode));

      return res ?? [];
    },
    {
      manual: true,
      onSuccess: data => {
        setAdmins(data);
      },
    },
  );

  // 更新应用权限
  const { run: updateAdmins, loading: adminLoading } = useRequest(
    async (params: { app_code: string; admins: string[] }) => await apiInterceptors(updateAppAdmins(params)),
    {
      manual: true,
      onSuccess: () => {
        message.success('更新成功');
      },
    },
  );

  // useEffect(() => {
  //   getListFiltered();
  // }, [getListFiltered]);

  return (
    <System>
      <Spin spinning={spinning}>
        <div className='h-screen w-full p-4 md:p-6 overflow-y-auto'>
          <div className='flex justify-between items-center mb-6'>
            <div className='flex items-center gap-4'>
              <Input
                variant='filled'
                value={filterValue}
                prefix={<SearchOutlined />}
                placeholder={t('please_enter_the_keywords')}
                onChange={onSearch}
                onPressEnter={onSearch}
                allowClear
                className='w-[230px] h-[40px] border-1 border-white backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
              />
            </div>

            <Button
              className='border-none text-white bg-button-gradient flex items-center'
              icon={<PlusOutlined className='text-base' />}
              onClick={handleCreate}
            >
              {t('create_role')}
            </Button>
          </div>
          <div className=' w-full flex flex-wrap pb-12 mx-[-8px]'>
            {roles.map(item => {
              return (
                <BlurredCard
                  key={item.app_code}
                  code={item.app_code}
                  name={item.app_name}
                  description={item.app_describe}
                  RightTop={
                    <div className='flex items-center gap-2'>
                      <InnerDropdown
                        menu={{
                          items: [
                            {
                              key: 'edit',
                              label: (
                                <span
                                  onClick={e => {
                                    e.stopPropagation();
                                    operate(item);
                                  }}
                                >
                                  {t('Edit')}
                                </span>
                              ),
                            },
                            {
                              key: 'del',
                              label: (
                                <span
                                  className='text-red-400'
                                  onClick={e => {
                                    e.stopPropagation();
                                    showDeleteConfirm(item);
                                  }}
                                >
                                  {t('Delete')}
                                </span>
                              ),
                            },
                          ],
                        }}
                      />
                    </div>
                  }
                  Tags={
                    <div>
                      <Tag color="purple">内置</Tag>
                      <Tag color="cyan">{item.team_mode}</Tag>
                    </div>
                  }
                  rightTopHover={false}
                  LeftBottom={
                    <div className='flex gap-2 text-[#828282]'>
                      <span>{item.owner_name}</span>
                      <span>•</span>
                      {item?.updated_at && <span>{moment(item?.updated_at).fromNow() + ' ' + t('update')}</span>}
                    </div>
                  }
                  scene=""
                  logo={item?.team_mode ==='native_app'? "/pictures/admin.png" :"/pictures/ordinary.png"}
                />
              );
            })}
            <div className='w-full flex justify-end shrink-0 pb-12'>
              <Pagination
                total={totalRef.current?.total_count || 0}
                pageSize={12}
                current={totalRef.current?.current_page}
                onChange={async (page, _page_size) => {
                  await initData({ page });
                }}
              />
            </div>
          </div>

          {open && (
            <CreateRoleModal
              open={open}
              onCancel={() => {
                setOpen(false);
              }}
              refresh={initData}
              type={modalType}
            />
          )}
        </div>
      </Spin>
    </System>
  );
}

